package com.gang.lingdian.syncronized;

/**
 * @author gyg
 * @version 1.0
 * @date 2021/8/28 下午5:14
 * @Description:
 */
//第一步 创建资源类 定义属性和方法
class Share{
    private int num = 0;

    // 加1

    public synchronized void incr() throws InterruptedException {
        //第二步 通知  判断  干活
        while (num != 0){
            // wait用在while中 如果用if判断存在虚假唤醒
            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName()+"--"+num);
        this.notifyAll();
    }

    public synchronized void decr() throws InterruptedException {
        while (num != 1){
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName()+"--"+num);
        this.notifyAll();
    }

    // 减1
}

public class ThreadDemo1 {


    public static void main(String[] args) {
        Share share =new Share();
        new Thread(()->{
            for (int i = 0; i <10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"AA").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DD").start();
    }

}
